package com.wbao.dianniu.ui;


import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.adapter.WorkExperienceAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.MyListView;
import com.wbao.dianniu.data.JobDetailData;
import com.wbao.dianniu.data.WorkExperienceData;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.listener.IJobCollectListener;
import com.wbao.dianniu.listener.IJobDetailListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.JobCollectManager;
import com.wbao.dianniu.manager.JobDetailManager;
import com.wbao.dianniu.manager.ShareSDKManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 个人简历
 * 
 * @author yejianjun
 * 
 */
public class JobDetailsActivity extends BaseActivity implements IJobDetailListener,IJobCollectListener{

	private LinearLayout waittingLayout;
	private ProgressBar waittingProBar;
	private TextView waittingTV;
	
	private JobDetailManager manager;
	private 	TextView tv_jobName;
	private 	LinearLayout layout_head;
	private 	ImageView iv_head;
	private 	TextView tv_iv_name;
	private 	TextView tv_label;
	private 	TextView tv_money;
	private 	TextView tv_trial ;
	private 	TextView tv_trial_ruel;
	private 	TextView tv_place;
	private 	TextView tv_years;
	private 	TextView tv_education;
	private 	MyListView mListView;
	private int jobId;
	private JobDetailData data;
	private Button applyButton;
	private Button shareBtn;
	private Dialog dialog;
	private ImageView ivCalled,ivSendMsg,ivCollect;
	private JobCollectManager collectManger;
	private WorkExperienceAdapter adapter;
	private List<WorkExperienceData> experienceList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.job_details, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		setTitleName(getResources().getString(R.string.resume));
		initWattingView();
		init();
		initData();
		data = new JobDetailData();
		manager = new JobDetailManager(this);
		manager.addJobDetailListener(this);
		jobId = getIntent().getIntExtra(GlobalContext.INTENT_JOB_ID, 0);
		manager.jobDetail(jobId,GlobalContext.accountId);
		collectManger = new JobCollectManager(this);
		collectManger.addJobCollectListener(this);
	}

	private void initWattingView(){
		waittingLayout = (LinearLayout) findViewById(R.id.waitting_layout);
		waittingProBar = (ProgressBar) findViewById(R.id.waitting_progress);
		waittingTV = (TextView) findViewById(R.id.waitting_text_desc);
	}
	
	private void init() {
		tv_jobName = (TextView) findViewById(R.id.job_name);
		layout_head = (LinearLayout) findViewById(R.id.user_head_layout);
		iv_head = (ImageView) findViewById(R.id.user_head);
		tv_iv_name = (TextView) findViewById(R.id.user_name);
		tv_label = (TextView) findViewById(R.id.user_label);
		tv_money = (TextView) findViewById(R.id.job_money);
		tv_trial = (TextView) findViewById(R.id.job_is_trial);
		tv_trial_ruel = (TextView) findViewById(R.id.job_trial_ruel);
		tv_place = (TextView) findViewById(R.id.job_place);
		tv_years = (TextView) findViewById(R.id.job_years);
		tv_education = (TextView) findViewById(R.id.job_education);
		mListView = (MyListView) findViewById(R.id.job_detail_listview);
		Button btn_jubao = (Button) findViewById(R.id.job_jubao);
		applyButton= (Button) findViewById(R.id.job_apply);
		ivCalled = (ImageView) findViewById(R.id.jobCalled);
		ivSendMsg = (ImageView) findViewById(R.id.jobSendMsg);
		ivCollect = (ImageView) findViewById(R.id.jobCollect);
		layout_head.setOnClickListener(this);
		btn_jubao.setOnClickListener(this);
		tv_trial_ruel.setOnClickListener(this);
		ivCalled.setOnClickListener(this);
		ivSendMsg.setOnClickListener(this);
		ivCollect.setOnClickListener(this);
		applyButton.setOnClickListener(this);
		
		shareBtn = getRightTextButton();
		shareBtn.setText(getResources().getString(R.string.share));
		shareBtn.setOnClickListener(this);
		
	}
	private void initData(){
		experienceList = new ArrayList<WorkExperienceData>();
		adapter = new WorkExperienceAdapter(this,1);
		mListView.setAdapter(adapter);
		setListViewHeightBasedOnChildren(mListView);
	}
	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.job_apply:		// 邀请面试
			if (!GlobalContext.isPerfectData) {
				showAuthLevel("您还未完善资料，请先完善资料！");
				return;
			}
			if (!GlobalContext.isIndustryAuthority) {
				showIndustryAuth("您还未行业认证，是否现在认证！");
				return;
			}
			Intent invitedIntent = new Intent();
			invitedIntent.putExtra(GlobalContext.INTENT_JOB_ID, data.getId());
			invitedIntent.setClass(JobDetailsActivity.this,	JobInviteActivity.class);
			startActivity(invitedIntent);
			break;
		case R.id.user_head_layout://点击头像
			Utils.intoHeadInfoActivity(data.getId(), JobDetailsActivity.this);
			break;
		case R.id.job_jubao:	//举报
			Intent jbIntent = new Intent();
			//类型3 举报求职简历
			jbIntent.putExtra(GlobalContext.INTENT_REPORT_TYPE, 3);
			jbIntent.putExtra(GlobalContext.INTENT_REPORT_OBJECTID, jobId);
			jbIntent.setClass(JobDetailsActivity.this, ReportActivity.class);
			startActivity(jbIntent);
			break;
		case R.id.right_button:	//分享
			// 调用分享内容
			String imageUrl;
			if(TextUtils.isEmpty(data.getHeadPic())){
				imageUrl = GlobalContext.cdndownUrl + "logo.png";
			}else{
				imageUrl = GlobalContext.cdndownUrl + data.getHeadPic();
			}
			String content = "应聘岗位：" + data.getPost() + "\n" + "工作经验：" + data.getExperience();
			ShareSDKManager.getInstance().showShare(this, content, 4, imageUrl, data.getId());
			break;
		case R.id.job_trial_ruel:	//规则
			Intent intent = new Intent();
			intent.setClass(JobDetailsActivity.this, TrialRuelActivity.class);
			startActivity(intent);
			break;
		case R.id.jobCalled:
			String mobile = data.getMobile();
			callDialog(mobile);
			break;
		case R.id.jobCollect:
			if(1 == data.getIscollect()){
				data.setIscollect(0);
				ivCollect.setImageResource(R.drawable.collection_icon);
				Notification.showToastMsg(this, "已取消收藏");
			}else{
				data.setIscollect(1);
				ivCollect.setImageResource(R.drawable.collected_icon);
				Notification.showToastMsg(this, "已收藏");
			}
			collectManger.jobCollect(GlobalContext.accountId, jobId);
			break;
		case R.id.jobSendMsg:	// 跳转到聊天窗口
			//跳转到聊天界面
			String appkey = getResources().getString(R.string.app_key);
			LoginSampleHelper.getInstance().openChat(this, GlobalContext.environment + String.valueOf(data.getId()), appkey);
			break;
		default:
			break;
		}
	}
	/**
	 * 显示行业认证弹出框
	 */
	private void showIndustryAuth(String msg) {
		dialog = new Dialog(this, R.style.custom_Dialog);
		Window win = dialog.getWindow();
		win.getDecorView().setPadding(3, 3, 3, 3);
		win.setGravity(Gravity.CENTER);
		View view = LayoutInflater.from(this).inflate(R.layout.custom_message_dialog, null);
		Button okBtn = (Button) view.findViewById(R.id.custom_msg_ok);
		Button cancelBtn = (Button) view.findViewById(R.id.custom_msg_cancel);
		TextView message = (TextView) view.findViewById(R.id.custom_msg_message);
		message.setText(msg);
		dialog.setContentView(view);
		dialog.setCancelable(true);
		dialog.show();
		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (null != dialog && dialog.isShowing()) {
					dialog.dismiss();
				}
				// 跳转到行业认证界面
				Intent intent = new Intent();
				intent.setClass(JobDetailsActivity.this, IndustryAuthActivity.class);
				startActivity(intent);
			}
		});
		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != dialog && dialog.isShowing()) {
					dialog.dismiss();
				}
			}
		});
	}
	/**
	 * 显示认证弹出框
	 */
	private void showAuthLevel(String msg) {
		dialog = new Dialog(this, R.style.custom_Dialog);
		Window win = dialog.getWindow();
		win.getDecorView().setPadding(3, 3, 3, 3);
		win.setGravity(Gravity.CENTER);
		View view = LayoutInflater.from(this).inflate(R.layout.custom_message_dialog, null);
		Button okBtn = (Button) view.findViewById(R.id.custom_msg_ok);
		Button cancelBtn = (Button) view.findViewById(R.id.custom_msg_cancel);
		TextView message = (TextView) view
				.findViewById(R.id.custom_msg_message);
		message.setText(msg);
		dialog.setContentView(view);
		dialog.setCancelable(true);
		dialog.show();
		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (null != dialog && dialog.isShowing()) {
					dialog.dismiss();
				}
				// 跳转到完善资料界面
				Intent intent = new Intent();
				intent.setClass(JobDetailsActivity.this, PerfectInfoActivity.class);
				startActivity(intent);
			}
		});
		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != dialog && dialog.isShowing()) {
					dialog.dismiss();
				}
			}
		});
	}
	
	/**
	 * 拨打电话
	 */
	private void callDialog(final String mobile){
		CustomDialog.Builder builder = new CustomDialog.Builder(this);  
		builder.setTitle(mobile);
        builder.setPositiveButton("呼叫", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int which) {  
                dialog.dismiss();  
                Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+mobile));
				startActivity(intent);
            }  
        });  
        builder.setNegativeButton("取消",  
                new android.content.DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int which) {  
                        dialog.dismiss();  
                    }  
                });  
        builder.create().show();  
	}
	

	@Override
	public void onJobDetailFailure(int errorCode, String errorMsg) {
		waittingLayout.setVisibility(View.VISIBLE);
		waittingProBar.setVisibility(View.GONE);
		waittingTV.setText("加载失败，请稍后再试...");
//		ErrorMsgHandler.getInstance().onErrorMsg(this, errorCode, errorMsg);
	}

	@Override
	public void onJobDetailSuccess(JobDetailData data) {
		if(null == data){
			waittingLayout.setVisibility(View.VISIBLE);
			waittingProBar.setVisibility(View.GONE);
			waittingTV.setText("数据为空...");
			return;
		}
		waittingLayout.setVisibility(View.GONE);
		this.data = data;
		display(data);
	}
	
	private void display(JobDetailData data){
		tv_jobName.setText(data.getPost() == null ? "": data.getPost());
		if(!TextUtils.isEmpty(data.getHeadPic())){
			PictureDownloadUtils.displayHeadImage(this,iv_head, data.getHeadPic());
		}
		tv_iv_name.setText(data.getRealName() == null ? "": data.getRealName());
		tv_label.setText(data.getLabel() == null ? "": data.getLabel());
		tv_money.setText(data.getSalary() == null ? "": data.getSalary());
		tv_trial.setText(data.getTryout() == null ? "" : data.getTryout());
		tv_place.setText(data.getAddress() == null ? "": data.getAddress());
		tv_years.setText(data.getExperience() == null ? "": data.getExperience());
		tv_education.setText(data.getEducation() == null ? "": data.getEducation());
		if (!TextUtils.isEmpty(data.getDescribe())) {
			experienceList = Utils.parseWorkData(data.getDescribe());
			adapter.setData(experienceList);
			setListViewHeightBasedOnChildren(mListView);
			adapter.notifyDataSetChanged();
		}
		if(1 == data.getIscollect()){
			ivCollect.setImageResource(R.drawable.collected_icon);
		}else{
			ivCollect.setImageResource(R.drawable.collection_icon);
		}
		
	}

	@Override
	public void onJobCollectFailure(int errorCode, String errorMsg) {
	}

	@Override
	public void onJobCollectSuccess() {
	}

	public void setListViewHeightBasedOnChildren(ListView listView) {   
        // 获取ListView对应的Adapter   
        int totalHeight = 0;   
        for (int i = 0, len = adapter.getCount(); i < len; i++) {   
            // listAdapter.getCount()返回数据项的数目   
            View listItem = adapter.getView(i, null, listView);   
            // 计算子项View 的宽高   
            listItem.measure(0, 0);    
            // 统计所有子项的总高度   
            totalHeight += listItem.getMeasuredHeight();    
        }   
        ViewGroup.LayoutParams params = listView.getLayoutParams();   
        params.height = totalHeight+ (listView.getDividerHeight() * (adapter.getCount() - 1));   
        // listView.getDividerHeight()获取子项间分隔符占用的高度   
        // params.height最后得到整个ListView完整显示需要的高度   
        listView.setLayoutParams(params);   
    } 
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
		public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
}
